package com.joysuccess.minaserver.minaserver;

import com.joysuccess.minaserver.minaserver.raw.SocketMesaageManager;
import com.joysuccess.minaserver.utils.SocketUtil;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.springframework.stereotype.Component;

/**
 * 字节数组编码器
 * @author shenchao
 */
@Component
public class ByteArrayEncoder extends ProtocolEncoderAdapter {
    @Override
    public void encode(IoSession session, Object message,
                       ProtocolEncoderOutput out) throws Exception {
        // TODO Auto-generated method stub

        byte[] body = message.toString().getBytes("GB2312");
        byte[] bodyLen = SocketUtil.intToByteArray(body.length);

        IoBuffer buffer = IoBuffer.allocate(256);
        buffer.setAutoExpand(true);

        //包头标记
        buffer.put(SocketMesaageManager.HEAD_MARK);
        //协议版本
        buffer.put(SocketMesaageManager.VERSION);
        //命令
        buffer.put(new byte[]{0,0,0,0});
        //包长
        buffer.put(bodyLen);
        //包体
        buffer.put(body);

        buffer.flip();
        out.write(buffer);
        out.flush();

        buffer.free();
    }
}
